var menugrid; //树对象
var oTable;//datatable表格对象
var bTable;
var currentUserid;  //用户id
var roleid;

//初始加载用户树
$(function () {
    $('#roleTab a:first').click(function () {
        initUserColumn(currentUserid);
    });
    initAllUser();
});

//初始化用户列表方法
function initAllUser(id) {
    $.ajax({
        url: _path + "/userColumn/initUser",
        type: "POST",
        async: false,
        dataType: "json",
        success: function (result) {
            if (result.msg == "success") {
                var array = result.userList;
                var html = new Array();
                var j = 0;
                for (var i = 0; i < array.length; i++) {
                	if(array[i].username !="superadmin"){
                      html.push('<a id="' + array[i].id + '" href="javascript:show(\'' + array[i].id + '\')" class="list-group-item">');
                      html.push('&nbsp;' + array[i].username);
                      html.push('</a>');
                    if (id && id === array[i].id)
                        j = i;
                	}
                }
                $("#sysUser").html(html.join(''));
                show(array[j].id, array[j].username, array[j].status, array[j].realname);
            }
        }
    });
}
function show(id) {
    this.currentUserid = id;
//    $("#" + id).siblings().removeClass("active");
//    $("#" + id).addClass("active");
//    initAllUser();
//    if ($('#roleTab li:first').hasClass("active"))
    	initUserColumn(id);
}

//========================角色用户===========================
function initUser() {
    if (oTable) {
        oTable.fnPageChange('first');
        return;
    }
    oTable = $("#dataList").DataTable({
        "sAjaxSource": _path + "/role/initUserRole",
        "fnServerParams": function (aoData) {
            aoData.push({ "name": "id", "value": roleid });
        },
        "sServerMethod": "POST",
        "sAjaxDataProp": "dataList",
        "aoColumns": [
            { "sTitle": "选择", "sWidth": "5%",
                "mData": function (obj) {
                    return "<input type='checkbox' value='" + obj.id + "'/>";
                }
            },
            { "sTitle": "用户名", "mData": "username", "sWidth": "15%" },
            { "sTitle": "组织单位", "mData": "organ.organame", "sWidth": "10%" },
            { "sTitle": "状态", "mData": "status", "sWidth": "10%",
                "mRender": function (data, type, full) {
                    var status = '';
                    switch (data) {
                        case '01':
                            status = "正常";
                            break;
                        case '02':
                            status = "禁用";
                            break;
                        default:
                            break;
                    }
                    return status;
                }},
            { "sTitle": "手机", "mData": "mobile", "sWidth": "15%" },
            { "sTitle": "操作", "sWidth": "20%",
                "mData": function (obj) {
                    var html = new Array();
                    html.push('<div style="width: 80px;">');
                    html.push('<a href="javascript:delUser(\'' + obj.id + '\',\'' + obj.username + '\')" class="btn default btn-xs purple">');
                    html.push('<i class="fa fa-edit"></i> 删除</a>');
                    html.push('</div>');
                    return html.join('');
                }
            }
        ]
    });
}
function initUsers() {
    if (bTable) {
        bTable.fnPageChange('first');
        return;
    }
    bTable = $("#addUserList").DataTable({
        "sAjaxSource": _path + "/role/findUsers",
        "fnServerParams": function (aoData) {
            aoData.push({ "name": "roleid", "value": roleid });
        },
        "sServerMethod": "POST",
        "sAjaxDataProp": "dataList",
        "aoColumns": [
            /*{ "sTitle": "选择", "sWidth": "5%",
             "mData": function(obj) {
             return "<input type='checkbox' value='"+obj.id+"'/>";
             }
             },*/
            { "sTitle": "用户名", "mData": "username", "sWidth": "15%" },
            { "sTitle": "组织单位", "mData": "organ.organame", "sWidth": "10%" },
            /*{ "sTitle": "性别", "mData": "gender", "sWidth": "10%",
             "mRender": function ( data, type, full ) {
             var gender = '';
             switch(data) {
             case '01': gender = "男"; break;
             case '02': gender = "女"; break;
             default: break;
             }
             return gender;
             }},*/
            { "sTitle": "状态", "mData": "status", "sWidth": "10%",
                "mRender": function (data, type, full) {
                    var status = '';
                    switch (data) {
                        case '01':
                            status = "正常";
                            break;
                        case '02':
                            status = "禁用";
                            break;
                        case '03':
                            status = "删除";
                            break;
                        case '04':
                            status = "锁定";
                            break;
                        default:
                            break;
                    }
                    return status;
                }},
            { "sTitle": "移动电话", "mData": "mobile", "sWidth": "10%" },
            /*{ "sTitle": "注册时间", "mData": "createTime", "sWidth": "10%" },*/
            { "sTitle": "操作", "sWidth": "20%",
                "mData": function (obj) {
                    var html = new Array();
                    html.push('<div style="width: 80px;">');
                    html.push('<a href="javascript:addUserToRole(\'' + obj.id + '\')" class="btn default btn-xs purple">');
                    html.push('<i class="fa fa-edit"></i> 添加</a>');
                    html.push('</div>');
                    return html.join('');
                }
            }
        ]
    });
}
function addUser() {
    initUsers();
    $('#modal_addUser').modal('show');
}
function addUserToRole(userids) {
    App.ajax(_path + "/role/addUserToRole", "roleid=" + this.roleid + "&userids=" + userids, function (data) {
        switch (data.statusCode) {
            case 200 :
                App.bubble(data.statusCode, "添加成功！");
                initUser();
                $('#modal_addUser').modal('hide');
                break;
            case 500 :
                App.bubble(data.statusCode, "添加失败！");
                break;
            default :
                alert("操作失败！");
                break;
        }
    });
}
function delUser(userid, username) {
    if (userid && userid.length > 0 && window.confirm("确认删除用户" + username + "？")) {
        App.ajax(_path + "/role/delUserFromRole", "roleid=" + this.roleid + "&userids=" + userid, function (data) {
            switch (data.statusCode) {
                case 200 :
                    App.bubble(data.statusCode, "删除成功！");
                    initUser();
                    break;
                case 500 :
                    App.bubble(data.statusCode, "删除失败！");
                    break;
                default :
                    alert("操作失败！");
                    break;
            }
        });
    }
}
function delUsers() {
    var inputs = $("input:checked", $("#dataList"));
    if (inputs.length > 0) {
        if (window.confirm("确认删除用户所选用户？")) {
            var ids = new Array();
            for (var i = 0, len = inputs.length; i < len; i++) {
                ids.push(inputs[i].value);
            }
            userids = ids.join();
            App.ajax(_path + "/role/delUserFromRole", "roleid=" + this.roleid + "&userids=" + userids, function (data) {
                switch (data.statusCode) {
                    case 200 :
                        App.bubble(data.statusCode, "删除成功！");
                        initUser();
                        break;
                    case 500 :
                        App.bubble(data.statusCode, "删除失败！");
                        break;
                    default :
                        alert("操作失败！");
                        break;
                }
            });
        }
    } else {
        alert("请选择要删除的记录！");
    }
}


//========================菜单权限===========================
function initUserColumn(id) {
    if (menugrid) {
    	checkUserColumn(id);
        return;
    }
    $.ajax({
        type: "post",
        url: _path + "/userColumn/listLhkColumn",
        success: function (data) {
            menugrid = $("#menugrid").ligerGrid({
                headerRowHeight: 36,
                rowHeight: 36,
                width: '99%',
                height: '89%',
                checkbox: false,
                alternatingRow: true,
                usePager: false,
                columns: [
                    { display: '选择', name: '', width: '4%', render: function (row) {
                    	var html='';
                    	html = '<input id="'+row.id+'" type="checkbox" name="cid" value="' + row.id + '" style="margin-top:5px" onclick="changeBox(\'' + row.id + '\')"/>';
                    	return html;
                    }},
                    { display: '栏目名称', name: 'menuname', width: '96%', align: 'left', render: function (row) {
                            return row.value0;
                    }}
                ], 
                data: data, tree: { columnName: 'menuname' }, 
                rownumbers: true
            });
            checkUserColumn(id);
        }
    });
}

function change(id) {
    if ($("#menugrid").find(":checkbox[value='" + id + "']").is(":checked"))
        App.ajax(_path + "/sysMenu/addRoleMenu?roleid=" + this.roleid + "&meunid=" + id);
    else
        App.ajax(_path + "/sysMenu/addRoleMenu?roleid=" + this.roleid + "&meunid=" + id);
}
function checkUserColumn(id) {
    var $Column = $("#menugrid");
    $Column.find(":checkbox").removeAttr("checked");
    App.ajax(_path + "/userColumn/findUserColumn?userid=" + id, '', function (data) {
        if (data && data.userColumn) {
            var userColumn = data.userColumn;
            for (var i = 0, len = userColumn.length; i < len; i++) {
            	$Column.find(":checkbox[value='" + userColumn[i] + "']").attr("checked", "checked");
            }
        }
    });
}
function changeBox(id) {
	if ($("#menugrid").find(":checkbox[value='" + id + "']").is(":checked")) {
		$("#menugrid").find(":checkbox[id='" + id + "']").attr("checked", "checked");
	} else {
		// 不选中
		$("#menugrid").find(":checkbox[id='" + id + "']").removeAttr("checked");
	}
}
/**
 *  @title : 保存
 */
function saveUserColumn() {
    var inputs = $("input[name='cid']:checked", $("#menugrid"));
    if (inputs.length > 0) {
        var id = new Array();
        for (var i = 0, len = inputs.length; i < len; i++) {
            id.push(inputs[i].value);
        }
        App.ajax(_path + "/userColumn/addUserColumn", "userid=" + this.currentUserid + "&cid=" + id.join(), function (data) {
            switch (data.statusCode) {
                case 200 :
                    App.bubble(data.statusCode, "保存成功！");
                    break;
                case 500 :
                    App.bubble(data.statusCode, "保存失败！");
                    break;
                default :
                    alert("操作失败！");
                    break;
            }
        });
    } else {
    	App.bubble(500, "请至少选择一个菜单！");
    }
}

/**
 * @title :全选
 * */
var _CHECKFLAG = true;
function onSelectAllClick() {
    $('input:checkbox[name="cid"]').each(function () {
        this.checked = _CHECKFLAG;
    });
    _CHECKFLAG = !_CHECKFLAG;
}
